package com.tanhua.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.intercepter.UserThreadLocal;
import com.tanhua.server.service.CommentsService;
import org.apache.dubbo.config.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentsServiceImpl implements CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    //分页查询动态评论
    @Override
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1.调用Api查询评论列表
        List<Comment> list = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        //2.判断评论数据是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4.stream流
        List<CommentVo> collect = list.parallelStream()
                .filter(comment ->
                        map.get(comment.getUserId()) != null)
                .map(comment ->
                        CommentVo.init(map.get(comment.getUserId()), comment)
                ).collect(Collectors.toList());
        //5、构造返回值
        return new PageResult(page, pagesize, 0l, collect);
    }

    /**
     *  发布评论
     * @param comment  评论内容
     * @param movementId  动态id
     */
    @Override
    public void pushComments(String comment, String movementId) {
        //1.获取操作用户id
        Long userId = UserThreadLocal.getUserId();
        //2.构造Comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());  //类型:评论
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = commentApi.save(comment1);
    }


    //对评论的点赞
    @Override
    public Integer likeComment(String commentId) {
        //1.调用api查询用户是否已经对评论点赞
        Long userId = UserThreadLocal.getUserId();
        Boolean hasComment = commentApi.hasLikeComment(commentId, userId, CommentType.LIKE);
        //2.如果已经点赞,抛出异常
        if (hasComment){
            //throw new BusinessException(ErrorResult.error());
            disLikeComment(commentId);
        }
        //3.调用Api保存点赞数据到MongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(commentId));  //点赞的评论的id
        comment.setUserId(userId);  //点赞的id用户
        comment.setCommentType(CommentType.LIKE.getType());  //点赞
        comment.setCreated(System.currentTimeMillis());
        //4.添加点赞返回总记录数
        Integer count = commentApi.saveComment(comment);
        //5.拼接redis的Key,将用户点赞数存入redis
        String key = "COMMENTS_INTERACT_KEY" + commentId;
        String hashKey = "COMMENT_LIKE_HASHKEY" + userId;
        redisTemplate.opsForHash().put(key,hashKey,1);
        //返回总记录数
        return count;
    }


    //取消对评论的点赞
    @Override
    public Integer disLikeComment(String commentId) {
        //1.首先查询自己有没有点赞,传入动态id,取消点赞用户,动态操作点赞的类型
        Long userId = UserThreadLocal.getUserId();
        Boolean aBoolean = commentApi.hasLikeComment(commentId, userId, CommentType.LIKE);
        //分析:没有点赞就点赞,点赞了就取消掉
        if (!aBoolean){
            throw new BusinessException(ErrorResult.error());
            //没有点赞:调用上诉方法点赞
           // likeComment(commentId);
        }
        //2.调用api取消点赞,获取并返回总记录数
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(commentId));   //评论的id
        comment.setUserId(userId);  //点赞的id用户
        comment.setCommentType(CommentType.LIKE.getType());  //点赞状态
        comment.setCreated(System.currentTimeMillis());
        //4.删除点赞返回总记录数
        Integer count = commentApi.deleteComment(comment);
        //5删除redis当中的点赞记录
        String key = "COMMENTS_INTERACT_KEY" + commentId;
        String hashKey = "COMMENT_LIKE_HASHKEY" + userId;
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

}
